package com.zr.inquiry.service.serviceimpl;

import com.zr.inquiry.mapper.InquiryMapper;
import com.zr.inquiry.model.*;
import com.zr.inquiry.service.InquiryService;
import com.zr.inquiryenum.*;
import com.zr.util.AllRecords;
import com.zr.util.ResultVo;
import com.zr.util.ResultVoBuilder;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by Administrator on 2019/12/27.
 */
@Service
public class InquiryServiceImpl implements InquiryService {

    @Autowired
    private InquiryMapper inquiryMapper;

    @Override
    public legalperson getPersonById(Integer legalPersonId) {
        legalperson lePer = inquiryMapper.queryById(legalPersonId);

        return lePer;
    }

    @Override
    public List<Supplier> getSupplier(String legalPersonCode) {

        List<Supplier> list = inquiryMapper.getSupplier(legalPersonCode);
        return list;
    }

    @Override
    public ResultVo getPage(inquirytotal inquirytotal) {

        List<inquiryend> list = inquiryMapper.getPage(inquirytotal);
        int count = inquiryMapper.getCount(inquirytotal);

        if (!CollectionUtils.isEmpty(list)) {
            for (inquiryend inq : list) {
                if (inq.getInquiryStatus() != null) {
                    if (inq.getInquiryStatus() == 0) {
                        inq.setInquiryStatusName("未报价");
                    }
                    if (inq.getInquiryStatus() == 10) {
                        inq.setInquiryStatusName("已保存");
                    }
                    if (inq.getInquiryStatus() == 20) {
                        inq.setInquiryStatusName("已提交");
                    }
                    if (inq.getInquiryStatus() == 30) {
                        inq.setInquiryStatusName("已审核");
                    }
                    if (inq.getInquiryStatus() == 40) {
                        inq.setInquiryStatusName("已作废");
                    }
                }

            }
        }

        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(list);
        allRecords.setTotalNumber(count);
        allRecords.setPageIndex(inquirytotal.getPageIndex());
        allRecords.setPageSize(inquirytotal.getPageSize());

        allRecords.resetTotalNumber(count);

       /* System.out.println(allRecords);*/
        return ResultVoBuilder.success(allRecords);
    }

    @Override
    public ResultVo getSupPage(SupplierPage supplierPage) {
        List<Supplier> list = inquiryMapper.getSupPage(supplierPage);
        int count = inquiryMapper.getSupCount(supplierPage);

        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(list);
        allRecords.setTotalNumber(count);
        allRecords.setPageIndex(supplierPage.getPageIndex());
        allRecords.setPageSize(supplierPage.getPageSize());

        allRecords.resetTotalNumber(count);

        /*System.out.println(allRecords);*/
        return ResultVoBuilder.success(allRecords);
    }

    @Override
    public ResultVo getSparPage(SparePage sparePage) {

        List<Spare> list = inquiryMapper.getSparePage(sparePage);
        int count = inquiryMapper.getSpareCount(sparePage);

        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(list);
        allRecords.setTotalNumber(count);
        allRecords.setPageIndex(sparePage.getPageIndex());
        allRecords.setPageSize(sparePage.getPageSize());

        allRecords.resetTotalNumber(count);

        System.out.println(allRecords);
        return ResultVoBuilder.success(allRecords);

    }

    @Override
    public ResultVo deleteInquiry(InquiryDelete inquiryDelete) {
        inquirytotal inquirytotal = inquiryMapper.queryByrequestId(inquiryDelete.getRequestForQuotationId());
        /*System.out.println(inquirytotal);*/
        if (inquirytotal != null) {
            inquiryMapper.updateInquiry(inquiryDelete);
            return ResultVoBuilder.success("作废成功");
        }

        return ResultVoBuilder.error("请求作废的对象不存在");
    }

    @Override
    public List<inquirytotal> queryById(String requestForQuotationId) {
        List<inquirytotal> list = inquiryMapper.queryByRid(requestForQuotationId);

        return list;

    }

    @Override
    public inquiryend seeInquiryTotal(Integer id) {

        inquiryend inq = inquiryMapper.seeInquiryTotal(id);

        /*币别*/
        if (inq.getCurrencyCode() != null) {
            for (currencyCodeEnum c : currencyCodeEnum.values()) {
                if (inq.getCurrencyCode() == c.getValue()) {
                    inq.setCurrencyCodeName(c.getName());
                }
            }
        }
        /*含税*/
        if (inq.getIsTax() != null) {
            for (IsTaxEnum t : IsTaxEnum.values()) {
                if (inq.getIsTax() == t.getValue()) {
                    inq.setIsTaxName(t.getName());
                }
            }
        }
        /*询价类型*/
        if (inq.getInquiryStatus() != null) {
            for (inquiryStatusEnum t : inquiryStatusEnum.values()) {
                if (inq.getType() == t.getValue()) {
                    inq.setTypeName(t.getName());
                }
            }
        }
        return inq;
    }

    @Override
    public List<InquirySpare> seeSpareInquiry(Integer id) {
        List<InquirySpare> insp = inquiryMapper.seeSpareInquiry(id);

        return insp;
    }

    @Override
    public List<InquirySupplier> seeSupplierInquiry(Integer id) {
        List<InquirySupplier> insp = inquiryMapper.seeSupInquier(id);

        return insp;
    }

    @Override
    public ResultVo shenHe(@Valid ShenHeInquiry shenHeInquiry) {

        int i = inquiryMapper.shenHe(shenHeInquiry);

       /* System.out.println(i);*/
        if (i > 0) {
            return ResultVoBuilder.success("审核成功");


        }

        return ResultVoBuilder.error("审核失败");
    }

    @Override
    public int updateStatus(StatusUpdate statusUpdate) {

        int i = inquiryMapper.updateStatus(statusUpdate);
        return i;
    }

    @Override
    public ResultVo pass(PassInquiry passInquiry) {
        int i = inquiryMapper.pass(passInquiry);

        System.out.println(i);
        if (i > 0) {
            return ResultVoBuilder.success("审批成功");


        }

        return ResultVoBuilder.error("审批失败");


    }

    @Override
    public inquirytotal getByRid(String requestForQuotationId) {
        inquirytotal inquiry = inquiryMapper.queryByrequestId(requestForQuotationId);

        return inquiry;
    }

    @Override
    public void deleteInSpare(int inid) {
        inquiryMapper.deleteInSpare(inid);
    }

    @Override
    public void deleteInSupplier(int inid) {
        inquiryMapper.deleteInSupplier(inid);
    }

    @Override
    public int insertInSpare(List<InquirySpare> spareList) {

        int i = inquiryMapper.insertInSpare(spareList);
        return 0;
    }

    @Override
    public int insertInSup(List<InquirySupplier> supplierList) {
        int i = inquiryMapper.insertInSup(supplierList);
        return 0;
    }

    @Override
    public ResultVo updateInquiryTotal(inquiryend inquiry) {

        ResultVo resultVo = check(inquiry);
        if (!resultVo.getSuccess()) {
            return resultVo;
        }
        //3.验证备件明细不能为空
        //4.验证供应商明细不能为空
        //5.验证备件明细不能重复
        //6.验证供应商明细不能重复
        ResultVo resultVo1 = checkRepeat(inquiry);
        if (!resultVo1.getSuccess()) {
            return resultVo;
        }
        //7.验证备件是否都存在
        //8.验证供应商是否都存在
        //9.验证法人是否存在
        ResultVo resultVo2 = checkCunZai(inquiry);
        if (!resultVo2.getSuccess()) {
            return resultVo;
        }
        //1.验证每个备件必须要有可以生产他的供应商
        ResultVo resultVo3 = checkSpare(inquiry);
        if (!resultVo3.getSuccess()) {
            return resultVo;
        }
        //2.验证每个供应商一定有一个它可以生产的备件
        ResultVo resultVo4 = checkSupplier(inquiry);
        if (!resultVo4.getSuccess()) {
            return resultVo;
        }
        int i = inquiryMapper.updateInquiryTotal(inquiry);
        if (i>0){
            return ResultVoBuilder.success();
        }
        return ResultVoBuilder.error("修改失败");
    }

    @Override
    public ResultVo addInquiry(@Valid inquiryend inquiry) {

        ResultVo resultVo = check(inquiry);
        if (!resultVo.getSuccess()) {
            return resultVo;
        }
        //3.验证备件明细不能为空
        //4.验证供应商明细不能为空
        //5.验证备件明细不能重复
        //6.验证供应商明细不能重复
        ResultVo resultVo1 = checkRepeat(inquiry);
        if (!resultVo1.getSuccess()) {
            return resultVo1;
        }
        //7.验证备件是否都存在
        //8.验证供应商是否都存在
        //9.验证法人是否存在
        ResultVo resultVo2 = checkCunZai(inquiry);
        if (!resultVo2.getSuccess()) {
            return resultVo2;
        }
        //1.验证每个备件必须要有可以生产他的供应商
        ResultVo resultVo3 = checkSpare(inquiry);
        if (!resultVo3.getSuccess()) {
            return resultVo3;
        }
        //2.验证每个供应商一定有一个它可以生产的备件
        ResultVo resultVo4 = checkSupplier(inquiry);
        if (!resultVo4.getSuccess()) {
            return resultVo4;
        }

        inquiryMapper.addInquiryTotal(inquiry);
        int id = inquiry.getId();
        List<InquirySupplier> supList = inquiry.getSupplierDetailsList();
        for (InquirySupplier inSup:supList) {
            inSup.setInquiryId(id);
        }

        List<InquirySpare> spareList = inquiry.getInquiryDetailsList();
        for (InquirySpare inspare:spareList) {
            inspare.setInquiryId(id);
        }
        inquiryMapper.insertInSup(supList);
        inquiryMapper.insertInSpare(spareList);

        return ResultVoBuilder.success();
    }

    @Override
    public ResultVo importPlanClass(MultipartFile file) throws Exception{

        //2.提示版本问题，询问产品经理支持哪种版本的导入格式，使用2007版本的导入模板，根据版本不同，poi导入技术的读取方式不同

        if (!file.getOriginalFilename().contains("xlsx")){
            return ResultVoBuilder.error("文档版本不同,请改为xlsx版本再试");
        }

        //3.模板是否是需要导入的模板，验证模板是否正确
        //通过获得文档里面的内容,进行判断,该文档是否正确
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取单元格中的信息 at0是获取sheet1中的数据。
        XSSFSheet sheet = workbook.getSheetAt(0);
        System.out.println(sheet.getRow(sheet.getFirstRowNum()).getCell(0));
        //验证第一列第一行的表格标头信息是否为 “询价单导入”，如果不是，提示模板错误。
        if (!String.valueOf(sheet.getRow(sheet.getFirstRowNum()).getCell(0)).equals("询价计划导入模板")) {
            return ResultVoBuilder.error("模板错误,请重新创建");
        }

        List<InquiryXSSFWork> inquiryList = new ArrayList<>();
        //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        for (int i = sheet.getFirstRowNum() + 3; i <= sheet.getLastRowNum(); i++) {
            //读取每一行的数据
            XSSFRow xssfRow = sheet.getRow(i);
            if(xssfRow!=null) {

                String test1 = String.valueOf(xssfRow.getCell(1)).trim();
                String test2 = String.valueOf(xssfRow.getCell(2)).trim();
                String test3 = String.valueOf(xssfRow.getCell(3)).trim();
                String test4 = String.valueOf(xssfRow.getCell(4)).trim();
                String test5 = String.valueOf(xssfRow.getCell(5)).trim();
                String test6 = String.valueOf(xssfRow.getCell(6)).trim();
                String test7 = String.valueOf(xssfRow.getCell(7)).trim();
                if (!test1.equals("")&&!test1.equals("null")
                        ||!test2.equals("")&&!test2.equals("null")
                        ||!test3.equals("")&&!test3.equals("null")
                        ||!test4.equals("")&&!test4.equals("null")
                        ||!test5.equals("")&&!test5.equals("null")
                        ||!test6.equals("")&&!test6.equals("null")
                        ||!test7.equals("")&&!test7.equals("null")){
                    //把每一行的数据放入到实体类中
                    ResultVo<InquiryXSSFWork> inquiryImportVo = build(xssfRow);
                    if (!inquiryImportVo.getSuccess()){
                        return inquiryImportVo;
                    }
                    //把实体类中的数据放入到list集合中
                    inquiryList.add(inquiryImportVo.getData());
                }

            }
        }

        ResultVo resultVo = checkRepeat2(inquiryList);
        if (!resultVo.getSuccess()){
            return resultVo;
        }

        System.out.println(inquiryList);
        return ResultVoBuilder.success(inquiryList);
    }

    private ResultVo checkRepeat2(List<InquiryXSSFWork> inquiryList) {

        List<String> codeList = new ArrayList<>();
        for (InquiryXSSFWork inquiry:inquiryList) {
            codeList.add(inquiry.getSpareCoding());
        }

        Set<String> codeSet = new HashSet<>(codeList);
        if (codeList.size()!=codeSet.size()){
            return ResultVoBuilder.error("文档中有重复备件");
        }

        return ResultVoBuilder.success();
    }

    public ResultVo build(XSSFRow xssfRow){
        InquiryXSSFWork inquiryXSSFWork = new InquiryXSSFWork();
        //     4.格式问题，必须保持统一格式，统一为字符串格式导入
        try {
            inquiryXSSFWork.setSpareCoding(String.valueOf(xssfRow.getCell(1)));
        }catch (Exception e){
            return ResultVoBuilder.error("请检查编码格式是否为字符串格式");
        }

        inquiryXSSFWork.setSpareName(String.valueOf(xssfRow.getCell(2)));
        inquiryXSSFWork.setMeasurementUnit(String.valueOf(xssfRow.getCell(3)));
        String inquiryQty = String.valueOf(xssfRow.getCell(4));
        double douQty = Double.parseDouble(inquiryQty);
        Integer intQty = (int)douQty;
        inquiryXSSFWork.setInquiryQty(intQty);

        System.out.println(intQty+"++++++++++++++");

        inquiryXSSFWork.setCurrencyCodeName(String.valueOf(xssfRow.getCell(5)));

        if (String.valueOf(xssfRow.getCell(5)).equals("人民币")){
            inquiryXSSFWork.setCurrencyCode(1);
        }
        if (String.valueOf(xssfRow.getCell(5)).equals("美元")){
            inquiryXSSFWork.setCurrencyCode(2);
        }

        String MOQ = String.valueOf(xssfRow.getCell(6));
        double douMOQ = Double.parseDouble(MOQ);
        Integer intMOQ = (int)douMOQ;
        inquiryXSSFWork.setMoq(intMOQ);

        System.out.println(intMOQ+"-------------");

        String deliveryCycle = String.valueOf(xssfRow.getCell(7));
        double douDeliveryCycle = Double.parseDouble(deliveryCycle);
        int intDeliveryCycle = (int)douDeliveryCycle;
        inquiryXSSFWork.setDeliveryCycle(intDeliveryCycle);

        System.out.println(intDeliveryCycle+"============");

        System.out.println(inquiryXSSFWork);
        return ResultVoBuilder.success(inquiryXSSFWork);
    }

    /*验证*/
    private ResultVo checkSupplier(@Valid inquiryend inquiry) {
        //2.验证每个供应商一定有一个它可以生产的备件
        List<String> suplist = new ArrayList<>();
        for (InquirySupplier inSup : inquiry.getSupplierDetailsList()) {
            suplist.add(inSup.getVendorCode());
        }
        List<String> splist = new ArrayList<>();
        for (InquirySpare inquirySpare : inquiry.getInquiryDetailsList()) {
            splist.add(inquirySpare.getSpareCoding());
        }
        /*全部的中间表信息*/
        List<SpareSupplier> spareSuppliers = inquiryMapper.querySpareSupByVenCodeList(suplist);
        /*把每个供应商能生产的备件信息*/
        for (String code : suplist) {
            /*每个供应商能生产的备件集合*/
            List<String> spareList = new ArrayList<>();
            for (SpareSupplier spareSupplier : spareSuppliers) {
                if (code.equals(spareSupplier.getVendorCode())) {
                    spareList.add(spareSupplier.getSpareCoding());
                }

            }
            if (Collections.disjoint(spareList, splist)) {
                return ResultVoBuilder.error("供应商编码为:" + code + "没有合法生产的备件,其合法备件为:" + spareList);
            }
        }
        return ResultVoBuilder.success();
    }

    private ResultVo checkSpare(@Valid inquiryend inquiry) {
        //1.验证每个备件必须要有可以生产他的供应商
        //(1).根据多个备件查询备件供应商中间表,查询这些备件都被那些供应商生产
        List<String> splist = new ArrayList<>();
        for (InquirySpare inquirySpare : inquiry.getInquiryDetailsList()) {
            splist.add(inquirySpare.getSpareCoding());
        }
        List<String> suplist = new ArrayList<>();
        for (InquirySupplier inquirySupplier : inquiry.getSupplierDetailsList()) {
            suplist.add(inquirySupplier.getVendorCode());
        }
        /*全部的中间表信息*/
        List<SpareSupplier> spareSuppliers = inquiryMapper.querySpareSupByCodeList(splist);
        /*把每一个备件能被生产的供应商找出来,放到集合中*/
        for (String code : splist) {
            /*每个备件的供应商集合*/
            List<String> supplierList = new ArrayList<>();
            for (SpareSupplier spareSupplier : spareSuppliers) {
                if (code.equals(spareSupplier.getSpareCoding())) {
                    supplierList.add(spareSupplier.getVendorCode());
                }
            }
            //disjoint判断交集,true:没有交集,false:有交集
            if (Collections.disjoint(supplierList, suplist)) {
                return ResultVoBuilder.error("备件编码为:" + code + "没有合法的供应商,其合法供应商为:" + supplierList);
            }
        }
        return ResultVoBuilder.success();
    }

    private ResultVo checkCunZai(@Valid inquiryend inquiry) {
        //7.验证备件是否都存在
        List<String> splist = new ArrayList<>();
        for (InquirySpare inquirySpare : inquiry.getInquiryDetailsList()) {
            splist.add(inquirySpare.getSpareCoding());
        }
        List<String> spareList = inquiryMapper.queryBySpCode(splist);
        if (spareList.size() != splist.size()) {
            splist.removeAll(spareList);
            return ResultVoBuilder.error("有不合法的备件,不合法备件为:" + splist);
        }
        //8.验证供应商是否都存在
        List<String> suplist = new ArrayList<>();
        for (InquirySupplier inSup : inquiry.getSupplierDetailsList()) {
            suplist.add(inSup.getVendorCode());
        }
        List<String> supplierList = inquiryMapper.queryBySupCode(suplist);
        if (supplierList.size() != suplist.size()) {
            suplist.removeAll(supplierList);
            return ResultVoBuilder.error("有不合法的供应商,不合法供应商为:" + suplist);
        }

        //9.验证法人是否存在
        legalperson legalperson = inquiryMapper.queryByPersonId(inquiry.getLegalPersonId());
        return ResultVoBuilder.success();
    }

    private ResultVo checkRepeat(@Valid inquiryend inquiry) {
        //5.验证备件明细不能重复
        List<String> splist = new ArrayList<>();
        List<InquirySpare> spareList = inquiry.getInquiryDetailsList();
        for (InquirySpare inSpare : spareList) {
            splist.add(inSpare.getSpareCoding());
        }
        /*Set<String> spareSet = new HashSet<>(splist);
        if (splist.size()!= spareSet.size()){
            return ResultVoBuilder.error("有重复的备件");
        }*/

        /*更高要求:将重复的备件编号输出出来*/
        List<String> newSpList = new ArrayList<>();
        List<String> repeatSpList = new ArrayList<>();
        for (String coding : splist) {
            if (newSpList.contains(coding)) {
                repeatSpList.add(coding);
            }
            newSpList.add(coding);
        }
        if (repeatSpList.size() > 0) {
            return ResultVoBuilder.error("有重复的备件,重复的编码为" + repeatSpList);
        }

        //6.验证供应商明细不能重复
        List<String> sulist = new ArrayList<>();
        List<InquirySupplier> supplierList = inquiry.getSupplierDetailsList();
        for (InquirySupplier inSup : supplierList) {
            sulist.add(inSup.getVendorCode());
        }

        List<String> newSupList = new ArrayList<>();
        List<String> repeatSupList = new ArrayList<>();
        for (String code : sulist) {
            if (newSupList.contains(code)) {
                repeatSupList.add(code);
            }
            newSupList.add(code);
        }
        if (repeatSupList.size() > 0) {
            return ResultVoBuilder.error("有重复的供应商,重复的编码为" + repeatSupList);
        }

        return ResultVoBuilder.success();
    }

    /*总验证*/
    private ResultVo check(@Valid inquiryend inquiry) {

        //10.验证询价类型、询价币别、是否含税、询价开始日期是否在结束日期之前
        ResultVo resultVo = checkEnum(inquiry);
        if (!resultVo.getSuccess()) {
            return resultVo;
        }

        return ResultVoBuilder.success();
    }

    /*enum验证*/
    private ResultVo checkEnum(@Valid inquiryend inquiry) {
        //10.验证询价类型、询价币别、是否含税、询价开始日期是否在结束日期之前
        if (TypeEnum.getName(inquiry.getInquiryStatus()) == null) {
            return ResultVoBuilder.error("询价状态不能为空");
        }
        if (IsTaxEnum.getName(inquiry.getIsTax()) == null) {
            return ResultVoBuilder.error("是否含税不能为空");
        }
        if (inquiryStatusEnum.getName(inquiry.getType()) == null) {
            return ResultVoBuilder.error("询价类型不能为空");
        }
        if (currencyCodeEnum.getName(inquiry.getCurrencyCode()) == null) {
            return ResultVoBuilder.error("币别不能为空");
        }

        /*验证日期*/
        int res = inquiry.getStartTime().compareTo(inquiry.getEndTime());
        if (res > 0) {
            return ResultVoBuilder.error("开始日期必须在结束日期之前");
        }

        return ResultVoBuilder.success();
    }


}
